<template>
  <div class="page_space btn_space">
    <p class="title_1">基本信息</p>
    <input-card>
      <inputItem
        v-model="params.name"
        :content="params.name"
        title="人员姓名"
        tip="请输入采样人员姓名"
        type="input"
      />
      <inputItem
        v-model="params.code"
        :content="params.code"
        title="人员编号"
        tip="请输入人员编号"
        type="input"
      />
      <inputItem
        v-model="params.userName"
        :content="params.userName"
        title="账号名称"
        tip="请输入账号名称"
        type="input"
      />
      <inputItem
        v-model="params.areaCodeName"
        :content="params.areaCodeName"
        title="所属区划"
        tip="请选择所属区划"
        type="select"
        @select="toSelect(0)"
      />
      <inputItem
        v-model="params.departmentIdName"
        :content="params.departmentIdName"
        title="所属部门"
        tip="请选择所属部门"
        type="select"
        @select="toSelect(1)"
      />
      <inputItem
        v-model="params.roleCodeName"
        :content="params.roleCodeName"
        title="职务角色"
        tip="请选择职务角色"
        type="select"
        @select="toSelect(2)"
      />
      <inputItem
        v-model="params.contactsTel"
        :content="params.contactsTel"
        title="联系电话"
        tip="请输入联系电话"
        type="input"
      />
      <inputItem
        v-model="params.identityNumber"
        :content="params.identityNumber"
        title="身份证号"
        tip="请输入身份证号"
        type="input"
      />
      <inputItem
        v-model="params.genderName"
        :content="params.genderName"
        title="性别（选填）"
        tip="请选择性别"
        type="select"
        @select="toSelect(3)"
      />
      <inputItem
        v-model="params.contactAddress"
        :content="params.contactAddress"
        title="联系地址（选填）"
        tip="请输入联系地址"
        type="input"
      />
      <input-item-textarea
        v-model="params.description"
        title="备注（选填）"
        tip="请输入备注"
      />
    </input-card>

    <p class="title_1">
      <span>资质信息</span>
      <span v-debounce class="right" @click="addQualification">添加</span>
    </p>
    <input-card v-if="params.qualification.length === 0">
      <div class="tip_add">
        <p>暂无资质信息</p>
        <button @click="addQualification">添加资质</button>
      </div>
    </input-card>
    <template v-else>
      <input-card
        v-for="(item, index) in params.qualification"
        :key="index"
        class="mb-15"
      >
        <inputItem
          v-model="item.fieldName"
          :content="item.fieldName"
          title="资质名称"
          tip="请输入资质名称"
          type="input"
        />
        <inputItem
          v-model="item.type"
          :content="item.type"
          title="资质类型"
          tip="请输入资质类型"
          type="input"
        />
        <inputItem
          :content="item.startDate"
          title="有效起始日期"
          tip="请选择有效起始日期"
          type="select"
          @select="selectTime(index, 'start')"
        />
        <inputItem
          :content="item.endDate"
          title="有效结束日期"
          tip="请选择有效结束日期"
          type="select"
          @select="selectTime(index, 'end')"
        />
        <input-item-upload title="资质文件" tip="支持上传 png，jpg，jpeg">
          <file-upload
            :imgId="item.fileId"
            :maxLen="1"
            deletable
            @change="uploadFile($event, index)"
          />
        </input-item-upload>
        <div class="btn_delete" @click="deleteQualification(index)">删除</div>
      </input-card>
    </template>

    <div class="btn_wrap">
      <button class="btn" @click="submit">提交</button>
    </div>

    <van-popup v-model="show" position="bottom" :round="true">
      <!-- 选择产地-->
      <template v-if="active === 0">
        <van-cascader
          v-model="cascaderValue"
          title=""
          :options="places"
          @close="show = false"
          @change="onChange"
          @finish="onFinish"
        />
      </template>
      <template v-if="active === 1">
        <van-picker
          ref="pickerForDepartment"
          title="请选择所属部门"
          show-toolbar
          :columns="departments"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmDepartment">确定</button>
        </div>
      </template>
      <template v-if="active === 2">
        <van-picker
          ref="pickerForRole"
          title="请选择职务角色"
          show-toolbar
          :columns="roleList"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmRole">确定</button>
        </div>
      </template>
      <template v-if="active === 3">
        <van-picker
          ref="pickerForGender"
          title="请选择性别"
          show-toolbar
          :columns="genderList"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmGender">确定</button>
        </div>
      </template>
      <template v-if="active === 4">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="submitTime">确定</button>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import inputItemUpload from '@/components/input-card/item-upload'
import { getAreaList, getDepartment, getDictionaryData } from '@/api/base'
import { saveOrUpdate, getPersonDetail } from '@/api/person'
import { ParseDate } from '@/utils'
import { validateIdCard, validateContactsTel } from '@/utils/validate'
import fileUpload from '@/components/file-upload'
import inputItemTextarea from '@/components/input-card/item-textarea'

export default {
  name: 'addPerson',
  components: {
    inputCard,
    inputItem,
    fileUpload,
    inputItemUpload,
    inputItemTextarea
  },
  data() {
    return {
      show: false,
      active: 0,
      // 区划 区码
      cascaderValue: '',
      // 产地选项
      places: [],
      departments: [], // 部门
      roleList: [], // 部门
      genderList: [], // 性别
      // 时间picker
      currentDate: new Date(),
      minDate: '',
      maxDate: '',
      targetTime: {
        index: '',
        type: ''
      },

      params: {
        id: '',
        code: '',
        name: '',
        userName: '',
        departmentId: '',
        departmentIdName: '',
        roleCode: '',
        roleCodeName: '',
        contactsTel: '',
        description: '',
        qualificationJson: '',
        qualification: [],
        areaCode: '',
        areaCodeName: '',
        gender: '',
        genderName: '',
        contactAddress: '',
        identityNumber: '',
        identityType: 'ShenFenZheng'
      },
      pageType: 'save'
    }
  },
  created() {
    // 时间
    this.minDate = new Date(this.getTime(-10))
    this.maxDate = new Date(this.getTime(10))

    this.getDepartment()
    this.getRoleList()
    this.getAreaList()
    this.getGenderList()
    const { id, type } = this.$route.query
    if (type === 'update' && id) {
      this.getPersonDetail(id)
      this.pageType = 'update'
      document.title = '从业人员编辑页'
    }
  },
  methods: {
    // 获取时间
    getTime(n = 0) {
      const t = new Date()
      t.setFullYear(t.getFullYear() + n)
      return t.toLocaleDateString()
    },
    // 更新时 获取详情
    async getPersonDetail(id) {
      const { code, data } = await getPersonDetail(id)
      if (code === '0') {
        this.params = {
          id: data.id,
          code: data.code,
          name: data.name,
          userName: data.userName,
          departmentId: data.departmentId,
          departmentIdName: data.departmentName,
          roleCode: data.roleCode,
          roleCodeName: data.roleName,
          contactsTel: data.contactsTel,
          description: data.description,
          qualificationJson: data.qualificationJson,
          areaCode: data.areaCode,
          areaCodeName: data.allAreaName,
          gender: data.gender,
          genderName: data.gender === 'man' ? '男' : '女',
          contactAddress: data.contactAddress,
          identityNumber: data.identityNumber,
          identityType: 'ShenFenZheng',
          qualification: data.qualificationList
        }
      }
    },
    uploadFile(e, index) {
      console.log(e, index)
      if (e.length !== 0) {
        this.params.qualification[index].fileId = e[0].fileId
        this.params.qualification[index].fileName = e[0].fileName
      } else {
        this.params.qualification[index].fileId = ''
        this.params.qualification[index].fileName = ''
      }
    },
    selectTime(index, type) {
      // 开始 不能大于结束
      if (type === 'start') {
        let endTime =
          this.params.qualification[index].endDate || this.getTime(10)
        this.maxDate = new Date(endTime)
      } else {
        // 结束 不能早于开始
        let startTime =
          this.params.qualification[index].startDate || this.getTime(-10)
        this.minDate = new Date(startTime)
      }
      this.show = true
      this.active = 4
      this.targetTime = {
        index,
        type
      }
    },
    // 确定-时间
    submitTime() {
      this.show = false
      let formatTime = ParseDate(this.currentDate)
      let index = this.targetTime.index
      if (this.targetTime.type === 'start') {
        let endTime = this.params.qualification[index].endDate
        if (endTime) {
          let newDate = new Date(formatTime)
          let endDate = new Date(endTime)
          if (newDate > endDate) {
            this.$toast('有效起始日期不可晚于有效结束日期')
            return false
          }
        }
        // 校验时间
        this.params.qualification[index].startDate = formatTime
      } else {
        let startTime = this.params.qualification[index].startDate
        if (startTime) {
          let newDate = new Date(formatTime)
          let startDate = new Date(startTime)
          if (newDate < startDate) {
            this.$toast('有效结束日期不可早于有效开始日期')
            return false
          }
        }
        this.params.qualification[index].endDate = formatTime
      }
    },
    async toSelect(e) {
      this.active = e
      this.show = true
    },
    // 校验
    validate() {
      // 必填项-基本信息
      let requiredOfBase = [
        {
          label: '人员姓名',
          key: 'name'
        },
        {
          label: '人员编号',
          key: 'code'
        },
        {
          label: '账号名称',
          key: 'userName'
        },
        {
          label: '所属区划',
          key: 'areaCodeName'
        },
        {
          label: '所属部门',
          key: 'departmentIdName'
        },
        {
          label: '职务角色',
          key: 'roleCodeName'
        },
        {
          label: '联系电话',
          key: 'contactsTel'
        },
        {
          label: '身份证号',
          key: 'identityNumber'
        }
      ]
      // 必填项-资质信息
      let requiredOfQualification = [
        {
          label: '资质名称',
          key: 'fieldName'
        },
        {
          label: '资质类型',
          key: 'type'
        },
        {
          label: '有效起始日期',
          key: 'startDate'
        },
        {
          label: '有效结束日期',
          key: 'endDate'
        },
        {
          label: '资质文件',
          key: 'fileId'
        }
      ]

      try {
        requiredOfBase.forEach((item) => {
          let value = this.params[item.key].trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })
        this.params.qualification.forEach((info) => {
          requiredOfQualification.forEach((item) => {
            let value = info[item.key].trim()
            if (value === '') {
              throw new Error(`${item.label} 为必填项！`)
            }
          })
        })

        // 正则校验
        if (!validateIdCard(this.params.identityNumber)) {
          throw new Error(`身份证号 格式不正确！`)
        }
        if (!validateContactsTel(this.params.contactsTel)) {
          throw new Error(`联系电话 格式不正确！`)
        }
        return true
      } catch (e) {
        this.$toast(e.message)
      }
    },
    // 提交
    async submit() {
      // 验证各字段是否为空
      if (!this.validate()) return false
      console.log(this.params)

      if (this.pageType === 'save') {
        console.log(this.params)
        this.params.qualificationJson = JSON.stringify(
          this.params.qualification
        )
        const { code } = await saveOrUpdate(this.params)
        if (code === '0') {
          this.$router.go(-1)
        }
      } else {
        console.log(this.params)
        this.params.qualificationJson = JSON.stringify(
          this.params.qualification
        )
        const { code } = await saveOrUpdate(this.params)
        if (code === '0') {
          this.$router.go(-1)
        }
      }
    },
    // 获取部门列表
    async getDepartment() {
      const { code, data } = await getDepartment()
      if (code === '0') {
        data.content.forEach((item) => {
          this.departments.push({
            text: item.departmentName,
            id: item.id
          })
        })
      }
    },
    // 获取角色
    async getRoleList() {
      const { code, data } = await getDictionaryData({
        dictionaryCode: 'TRACE_ROLE_TYPE'
      })
      if (code === '0') {
        data.content.forEach((item) => {
          this.roleList.push({
            text: item.dictDataName,
            id: item.dictDataCode
          })
        })
      }
    },
    // 获取区划
    async getAreaList() {
      const { code, data } = await getAreaList({ parentAreaCode: '440900' })
      if (code === '0') {
        this.places = []
        data.forEach((item) => {
          this.places.push({
            text: item.areaName,
            value: item.areaCode
          })
        })
      }
    },
    // 获取性别列表
    async getGenderList() {
      const { code, data } = await getDictionaryData({
        dictionaryCode: 'TRACE_USER_GENDER'
      })
      if (code === '0') {
        data.content.forEach((item) => {
          this.genderList.push({
            text: item.dictDataName,
            id: item.dictDataCode
          })
        })
      }
    },
    // 确定性别
    confirmGender() {
      let { id, text } = this.$refs.pickerForGender.getValues()[0]
      this.show = false
      this.params.gender = id
      this.params.genderName = text
    },
    // 确定角色
    confirmRole() {
      let { id, text } = this.$refs.pickerForRole.getValues()[0]
      this.show = false
      this.params.roleCode = id
      this.params.roleCodeName = text
    },
    // 确定部门
    confirmDepartment() {
      let { id, text } = this.$refs.pickerForDepartment.getValues()[0]
      this.show = false
      this.params.departmentId = id
      this.params.departmentIdName = text
    },
    // 添加资质
    addQualification() {
      this.params.qualification.push({
        fieldName: '',
        type: '',
        fileName: '',
        fileId: '',
        startDate: '',
        endDate: ''
      })
      this.$toast.success('添加成功')
    },
    // 删除资质
    deleteQualification(index) {
      this.$dialog
        .alert({
          title: '是否删除该资质信息?',
          showCancelButton: true
        })
        .then(() => {
          this.params.qualification.splice(index, 1)
          this.$toast.success('删除成功')
        })
        .catch(() => {
          // on cancel
        })
    },
    // 检测区划改变
    async onChange({ value, selectedOptions, tabIndex }) {
      const { code, data } = await getAreaList({
        parentAreaCode: value
      })
      let placeIndex = ''
      let target = {}

      if (tabIndex > 0) {
        for (let i = 0; i <= tabIndex; i++) {
          if (selectedOptions[i].parentIndex !== undefined) {
            let parentIndex = selectedOptions[i].parentIndex
            console.log('parentIndex:', parentIndex)
            target = this.places[parentIndex].children
          }
        }
        placeIndex = target.findIndex((item) => item.value === value)
        target = target[placeIndex]
      } else {
        placeIndex = this.places.findIndex((item) => item.value === value)
        target = this.places[placeIndex]
      }

      if (code === '0') {
        data.forEach((item) => {
          if (tabIndex < 1) {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              children: [],
              parentIndex: placeIndex
            })
          } else {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              parentIndex: placeIndex
            })
          }
        })
      }
    },
    // 区划完成
    onFinish({ selectedOptions }) {
      this.params.areaCodeName =
        selectedOptions.map((option) => option.text).join('') || ''
      // 获取区划码
      this.params.areaCode = selectedOptions[selectedOptions.length - 1].value
      console.log('finish')
      console.log(selectedOptions.map((option) => option.text).join('') || '')
      console.log(this.params.areaCodeName)
      this.show = false
    }
  }
}
</script>

<style scoped lang="scss">
.btn_delete {
  text-align: center;
  color: rgba(255, 4, 4, 1);
  font-size: 14px;
}

// 暂无供货信息
.tip_add {
  text-align: center;
  margin: 10px 0;

  p {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 粤商通/常见灰色 */
    color: #b2b8bd;
    margin-bottom: 10px;
  }

  button {
    background: #2163e0;
    height: 28px;
    padding: 5px 15px;
    border-radius: 15px;
    color: #fff;
    font-family: PingFang SC Medium;
    font-size: 13px;
    font-weight: normal;
    line-height: 13px;
    letter-spacing: 0px;
  }

  .plus {
    font-size: 18px;
    font-weight: bolder;
    padding-right: 2px;
  }
}

// 附件
.attachment {
  .title {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 一级标题颜色 */
    color: #171819;
  }

  .tip {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 大灰 */
    color: #656c74;
  }

  .box {
    padding-top: 16px;
    padding-bottom: 14px;
    border-width: 0 0 0.5px 0;
    border-style: solid;
    border-color: #ebebeb;
  }
}
</style>
